import { adminLoginAPI } from "@/api/admin";
import { UPDATE_USER_INFO } from "./types";
import { initUserInfo } from "./types"

export default {
    // 登录并更新userInfo
    // 1. 先登录  2. 登录成功之后更新userInfo   3. 将数据存储到localStorage => authority
    loginAndUpdateUserInfo(context,payload){  // 接收的参数用于登录
      let {commit} = context;

      // 方法返回一个promise实例
      return adminLoginAPI(payload).then(res => { 
          console.log("登录成功:actions", res);   // res.data
          localStorage.setItem("authority",JSON.stringify(res.data));
          commit(UPDATE_USER_INFO,res.data);
      })
    },
    // 退出登录
    exitAndAndUpdateUserInfo(context){
      let {commit} = context;

      // 删除localStorage中存储的数据
      localStorage.removeItem("authority");
      /* commit(UPDATE_USER_INFO,{
        adminname: "",
        role: null,
        token: "",
        checkedkeys: null,
      }); */
      commit(UPDATE_USER_INFO,initUserInfo());
    },
    // 每次刷新时,判断localStorage是否存在authority选项 -> 有 -> 将数据同步到vuex
    initAndUpdateUserInfo(context){
      console.log(111111,"initAndUpdateUserInfo执行了" );
      let {commit} = context;
      var authority = localStorage.getItem("authority");
      if(authority){
        // JSON.parse(authority)
        commit(UPDATE_USER_INFO,JSON.parse(authority));
      }
    }

  }